package cn.ys.org.service.impl;

import cn.ys.base.util.PageList;
import cn.ys.org.domain.Department;
import cn.ys.org.mapper.DepartmentMapper;
import cn.ys.org.query.DepartmentQuery;
import cn.ys.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> findAll() {
        return departmentMapper.findAll();
    }

    @Override
    public Department findById(Long id) {
        return departmentMapper.findById(id);
    }

    @Override
    public void add(Department department) {
        departmentMapper.add(department);
    }

    @Override
    public void update(Department department) {
        departmentMapper.update(department);
    }

    @Override
    public void delete(Long id) {
        departmentMapper.delete(id);
    }

    @Override
    public PageList<Department> queryByPage(DepartmentQuery query) {
        Integer totals = departmentMapper.queryByCount(query);
        if (null == totals || 0 == totals) {
            return new PageList<Department>(0, new ArrayList<>());
        }
        List<Department> rows = departmentMapper.queryByPage(query);
        return new PageList<>(totals, rows);
    }

    // 批量删除
    @Override
    public void piDeleteById(List<Long> ids) {
        departmentMapper.piDeleteById(ids);
    }


    @Override
    public List<Department> deptTree() {
        // 查询所有数据
        List<Department> allDepts = departmentMapper.findAll();
        Map<Long, Department> deptMap = allDepts.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
        List<Department> result = new ArrayList<>();
        for (Department dept : allDepts) {
            if (null == dept.getParentId()){
                result.add(dept);
            }else {
                Department parent = deptMap.get(dept.getParentId());
                if (null != parent){
                    parent.getChildren().add(dept);
                }
            }
        }
        return result;
    }
}
